<template>
  <div class="attachment-manager">
    <el-upload
      class="upload-btn"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :disabled="!draftId"
      accept="*"
    >
      <el-button type="primary" :disabled="!draftId">上传附件</el-button>
      <span v-if="!draftId" class="tip">请先保存草稿后上传附件</span>
    </el-upload>
    <el-table
      v-if="attachments.length"
      :data="attachments"
      border
      size="small"
      class="attach-table"
      style="margin-top: 12px"
    >
      <el-table-column prop="file_name" label="文件名" min-width="180" />
      <el-table-column prop="file_size" label="大小" width="80">
        <template #default="{ row }">
          {{ (row.file_size / 1024).toFixed(1) }} KB
        </template>
      </el-table-column>
      <el-table-column prop="uploaded_at" label="上传时间" width="160" />
      <el-table-column label="操作" width="140">
        <template #default="{ row }">
          <el-button size="small" @click="download(row)" type="success" plain>下载</el-button>
          <el-button size="small" @click="remove(row)" type="danger" plain>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-else class="empty-tip">暂无附件</div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { uploadAttachmentAPI, downloadAttachmentAPI, deleteAttachmentAPI, getAttachmentListAPI, type AttachListItem } from '@/api/attachAPI'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const props = defineProps<{
  draftId: number | null
}>()

const userStore = useUserStore()
const attachments = ref<AttachListItem[]>([])
const loading = ref(false)

const fetchList = async () => {
  if (!props.draftId) {
    attachments.value = []
    return
  }
  const res = await getAttachmentListAPI(props.draftId, userStore.id||'', userStore.token||'')
  if (res.code === 200) {
    attachments.value = res.data
  }
}

const beforeUpload = async (file: File) => {
  if (!props.draftId) {
    ElMessage.warning('请先保存草稿')
    return false
  }
  loading.value = true
  try {
    console.log(file);
    console.log(props.draftId);
    console.log(userStore.id);
    console.log(userStore.token);


    const res = await uploadAttachmentAPI(file, props.draftId, userStore.id||'', userStore.token||'')
    if (res.code === 200) {
      ElMessage.success('上传成功')
      fetchList()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (e) {
    ElMessage.error('上传失败'+e)
  } finally {
    loading.value = false
  }
  return false // 阻止 el-upload 默认上传
}

const download = async (row: AttachListItem) => {
  try {
    const blob = await downloadAttachmentAPI(row.file_name, row.id, userStore.id||'', userStore.token||'')
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = row.file_name
    a.click()
    window.URL.revokeObjectURL(url)
  } catch (e) {
    ElMessage.error('下载失败'+e)
  }
}

const remove = async (row: AttachListItem) => {
  try {
    const res = await deleteAttachmentAPI(row.id, userStore.id||'', userStore.token||'')
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchList()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (e) {
    ElMessage.error('删除失败'+e)
  }
}

watch(() => props.draftId, fetchList, { immediate: true })
</script>

<style scoped>
.attachment-manager {
  margin-top: 16px;
  background: #fafbfc;
  border-radius: 6px;
  padding: 16px 18px 10px 18px;
  border: 1px solid #eee;
}
.upload-btn {
  margin-bottom: 0;
}
.tip {
  color: #aaa;
  margin-left: 10px;
  font-size: 13px;
}
.attach-table {
  margin-top: 12px;
}
.empty-tip {
  color: #bbb;
  font-size: 14px;
  margin-top: 12px;
  text-align: center;
}
</style>
